package leetcode.d_100_199;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

// https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal
// 二叉树的锯齿形层次遍历
public class P103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> curRes = new LinkedList<>();
            for (int i=0; i<size; i++) {
                TreeNode node = queue.poll();
                if (res.size() % 2 == 0) {
                    // 正序
                    curRes.addLast(node.val);
                }else {
                    // 倒序
                    curRes.addFirst(node.val);
                }

                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            res.add(curRes);
        }
        return res;
    }
}
